import React, { useState, useCallback, useRef, useEffect } from 'react';
import { Chat, Select, Toast } from '@douyinfe/semi-ui';
import { ChartApi } from '@/api/index'; // Replace with actual API library

const ChartDom = ({ agentList }) => {
    const [activeAgentInfo, setActiveAgentInfo] = useState({ id: 1 });

    const handleOfAgentChange = (value) => {
        const selectedAgent = agentList.find((item) => item.id === value);
        if (selectedAgent) {
            setActiveAgentInfo({ id: selectedAgent.id, name: selectedAgent.name });
        }
    };

    const getId = () => Math.random().toString(36).substr(2, 9);
    const [mode, setMode] = useState('bubble');
    const [align, setAlign] = useState('leftRight');
    const defaultMessage = [
        {
            role: 'assistant',
            id: '1',
            createAt: 1715676751919,
            content: "你好，今天能帮你什么？",
        },
    ];
    const [hints, setHints] = useState([]);
    const onHintClick = useCallback((content) => {
        setHints([]);
        setMessage((message) => {
            return [
                ...message,
                {
                    role: 'assistant',
                    status: 'loading',
                    createAt: Date.now(),
                    id: getId()
                }
            ]
        });

        chartInfo.current.isChat = true;
        chartInfo.current.question = content;
        chartInfo.current.startTime = Date.now();

        generateMockResponse(content);
    }, []);
    const [message, setMessage] = useState(defaultMessage);
    const roleInfo = {
        user: {
            name: 'User',
            avatar: 'https://lf3-static.bytednsdoc.com/obj/eden-cn/ptlz_zlp/ljhwZthlaukjlkulzlp/docs-icon.png'
        },
        assistant: {
            name: activeAgentInfo.name || 'LinQ AI',
            avatar: './imgs/logo.svg'
        },
        system: {
            name: 'System',
            avatar: 'https://lf3-static.bytednsdoc.com/obj/eden-cn/ptlz_zlp/ljhwZthlaukjlkulzlp/other/logo.png'
        }
    }
    const globalController = useRef();
    const onChatsChange = useCallback((chats) => {
        setMessage(chats);
    }, []);

    const generateMockResponse = useCallback((content) => {
        const msgBody = {
            agent_id: activeAgentInfo.id,
            messages: [{
                role: "user",
                timestamp: Date.now(),
                content: content
            }]
        }
        const controller = new AbortController();
        const signal = controller.signal;
        globalController.current = controller;
        // requestChart(apiChat, msgBody, signal, async (resData) => {
        //     const { status, reader, error } = resData;
        //     if (status !== 200) {
        //         setMessage((message) => {
        //             return [
        //                 ...message,
        //                 {
        //                     role: 'assistant',
        //                     id: 'error',
        //                     content: '服务繁忙，暂时不可用',
        //                     status: 'error'
        //                 }
        //             ]
        //         });
        //         return;
        //     } else if (status === 200) {
        //         const decoder = new TextDecoder();
        //         let buffer = '';
        //         let lineNumber = 0, renderNumber = 0, tokenNumber = 0, finalContent = "";

        //         while (true) {
        //             const { done, value } = await reader.read();
        //             console.log("reader2", done, value);
        //             if (done) {
        //                 break;
        //             }
        //             buffer += decoder.decode(value);
        //             const messages = buffer.split('\n\n');
        //             buffer = messages.pop(); // 不能删除，否则会有重复数据

        //             for (const message of messages) {
        //                 await new Promise(resolve => setTimeout(resolve, 10));

        //                 if (message.startsWith('data:')) {
        //                     const data = message.slice(5).trim();
        //                     try {
        //                         const dataContent = JSON.parse(data);
        //                         if (!dataContent || typeof dataContent.content !== 'string') {
        //                             console.warn('Invalid data content format:', dataContent);
        //                             continue;
        //                         }

        //                         let chunk = dataContent.content;
        //                         if (chunk.includes("\n")) {
        //                             chunk = chunk.replace(/\n+/g, '\n');
        //                         }

        //                         finalContent += chunk;
        //                         chartInfo.current.tokenNumber++;
        //                         chartInfo.current.finalContent = finalContent;

        //                         console.log('finalContent:', finalContent);
        //                         setMessage((message) => {
        //                             const lastMessage = message[message.length - 1];
        //                             let newMessage = { ...lastMessage };
        //                             if (lastMessage.status === 'loading') {
        //                                 newMessage = {
        //                                     ...newMessage,
        //                                     content: `mock Response for ${content} \n`,
        //                                     status: 'incomplete'
        //                                 }
        //                             } else if (lastMessage.status === 'incomplete') {
        //                                 if (chunk === "[DONE]") {
        //                                     newMessage = {
        //                                         ...newMessage,
        //                                         status: 'complete',
        //                                         content: `${finalContent}`
        //                                     }
        //                                     // resetChartInfo();
        //                                 } else {
        //                                     newMessage = {
        //                                         ...newMessage,
        //                                         content: `${finalContent}`
        //                                     }
        //                                 }
        //                             }
        //                             return [...message.slice(0, -1), newMessage]
        //                         });


        //                     } catch (error) {
        //                         console.error('Failed to parse SSE data:', data, error);
        //                         continue;
        //                     }
        //                 }
        //                 console.log(messages);
        //             }
        //         }
        //     }
        // })
        ChartApi.postChart(msgBody, signal, async (res) => {
            console.log('对话信息111:', res);
            const { status, reader } = res;
            if (status !== 200) {
                setMessage((message) => {
                    return [
                        ...message,
                        {
                            role: 'assistant',
                            id: 'error',
                            content: '服务繁忙，暂时不可用',
                            status: 'error'
                        }
                    ]
                });
                return;
            } else if (status === 200) {
                const decoder = new TextDecoder();
                let buffer = '';
                let lineNumber = 0, renderNumber = 0, tokenNumber = 0, finalContent = "";

                while (true) {
                    const { done, value } = await reader.read();
                    console.log("reader2", done, value);
                    if (done) {
                        break;
                    }
                    buffer += decoder.decode(value);
                    const messages = buffer.split('\n\n');
                    buffer = messages.pop(); // 不能删除，否则会有重复数据

                    for (const message of messages) {
                        await new Promise(resolve => setTimeout(resolve, 10));

                        if (message.startsWith('data:')) {
                            const data = message.slice(5).trim();
                            try {
                                const dataContent = JSON.parse(data);
                                if (!dataContent || typeof dataContent.content !== 'string') {
                                    console.warn('Invalid data content format:', dataContent);
                                    continue;
                                }

                                let chunk = dataContent.content;
                                if (chunk.includes("\n")) {
                                    chunk = chunk.replace(/\n+/g, '\n');
                                }

                                finalContent += chunk;
                                chartInfo.current.tokenNumber++;
                                chartInfo.current.finalContent = finalContent;

                                console.log('finalContent:', finalContent);
                                setMessage((message) => {
                                    const lastMessage = message[message.length - 1];
                                    let newMessage = { ...lastMessage };
                                    if (lastMessage.status === 'loading') {
                                        newMessage = {
                                            ...newMessage,
                                            content: `mock Response for ${content} \n`,
                                            status: 'incomplete'
                                        }
                                    } else if (lastMessage.status === 'incomplete') {
                                        if (chunk === "[DONE]") {
                                            newMessage = {
                                                ...newMessage,
                                                status: 'complete',
                                                content: `${finalContent}`
                                            }
                                            // resetChartInfo();
                                        } else {
                                            newMessage = {
                                                ...newMessage,
                                                content: `${finalContent}`
                                            }
                                        }
                                    }
                                    return [...message.slice(0, -1), newMessage]
                                });


                            } catch (error) {
                                console.error('Failed to parse SSE data:', data, error);
                                continue;
                            }
                        }
                        console.log(messages);
                    }
                }
            }
        });
    }, []);

    const onMessageSend = useCallback(async (content, attachment) => {
        setMessage((message) => {
            return [
                ...message,
                {
                    role: 'assistant',
                    status: 'loading',
                    createAt: Date.now(),
                    id: getId()
                }
            ]
        });

        chartInfo.current.isChat = true;
        chartInfo.current.question = content;
        chartInfo.current.startTime = Date.now();

        generateMockResponse(content);
    }, []);
    const onMessageReset = useCallback((e) => {
        // setMessage((message) => {
        //     return [
        //        ...message,
        //         {
        //             role: 'assistant',
        //             status: 'loading',
        //             createAt: Date.now(),
        //             id: getId()
        //         }
        //     ]
        // });

        chartInfo.current.isChat = true;
        chartInfo.current.startTime = Date.now();

        generateMockResponse(chartInfo.current.question);
    })
    const uploadTipProps = { content: '自定义上传按钮提示信息' };
    const chartInfo = useRef({ question: '', finalContent: '', userChatId: 0, startTime: 0, tokenNumber: 0, isChat: false });
    const resetChartInfo = () => {
        chartInfo.current.question = '';
        chartInfo.current.finalContent = '';
        chartInfo.current.userChatId = 0;
        chartInfo.current.startTime = 0;
        chartInfo.current.tokenNumber = 0;
        chartInfo.current.isChat = false;
    };
    const onStopGenerator = useCallback((message) => {
        if (chartInfo.current.isChat) {
            globalController.current.abort(); // 终止请求
            const endTime = Date.now();
            const spendTime = endTime - chartInfo.current.startTime;
            const params = {
                question: chartInfo.current.question,
                answer: chartInfo.current.finalContent,
                agent_id: activeAgentInfo.id,
                end_type: 2,
                token: chartInfo.current.tokenNumber,
                time_consume: spendTime,
                parent_id: chartInfo.current.userChatId
            };
            ChartApi.postChartCallback(params).then((res) => {
                console.log('对话信息:', res);
                if (res.code === 0) {
                    chartInfo.current.userChatId = res.data.id;
                    setMessage((message) => {
                        const lastMessage = message[message.length - 1];
                        if (lastMessage.status && lastMessage.status !== 'complete') {
                            const lastMessage = message[message.length - 1];
                            let newMessage = { ...lastMessage };
                            newMessage.status = 'complete';
                            return [
                                ...message.slice(0, -1),
                                newMessage
                            ]
                        } else {
                            return message;
                        }
                    });
                }
            });
        }
    }, [chartInfo]);

    const getQuestionList = () => {
        ChartApi.getQuestionList({ category_id: 1 }).then((res) => {
            console.log('获取问题列表:', res);
            if (res.code === 0) {
                setHints((res.data.list || []).map((item) => (item.question + (item.prompt ? '(' + item.prompt + ')' : ''))));
            } else {
                console.error('获取问题列表失败:', res.msg);
                Toast.error('获取问题列表失败，请稍后重试');
            }
        })
    };

    useEffect(() => {
        getQuestionList();
    }, []);

    // 使用 useEffect 控制副作用调用
    useEffect(() => {
        if (agentList.length > 0) {
            const index = agentList.length - 1;
            setActiveAgentInfo({
                id: agentList[index].id,
                name: agentList[index].name
            });
        }
    }, [agentList]);

    return (
        <Chat
            className="chatDom"
            key={align + mode}
            align={align}
            mode={mode}
            chats={message}
            roleConfig={roleInfo}
            hints={hints}
            onHintClick={onHintClick}
            onChatsChange={onChatsChange}
            onMessageSend={onMessageSend}
            onMessageReset={onMessageReset}
            uploadTipProps={uploadTipProps}
            showStopGenerate={true}
            onStopGenerator={onStopGenerator}
            bottomSlot={
                <div className="bottomSlot">
                    <Select
                        value={activeAgentInfo.id}
                        onChange={handleOfAgentChange}
                        style={{ width: 150 }}
                        position="topLeft"
                    >
                        {
                            agentList.map((item) => {
                                return <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>
                            })
                        }
                    </Select>
                </div>
            }
        />
    );
};

export default ChartDom;